#include <stdlib.h>
#include <clutter/clutter.h>

#define WINDOWS_WIDTH 400
#define WINDOWS_HEIGHT 400
#define UNUSED(x) (void)x

static void reverse_timeline (ClutterTimeline *timeline, gpointer user_data)
{
    static int width = 0;
    static int step = 3;
    ClutterActor *progress_rect = user_data;

    if( width < 0 )
    {
        step = 3;
    }
    else if( width >= 150 )
    {
        step = -3;
    }

    width += step;

    ClutterTimelineDirection dir = clutter_timeline_get_direction (timeline);

    if (dir == CLUTTER_TIMELINE_FORWARD)
        dir = CLUTTER_TIMELINE_BACKWARD;
    else
        dir = CLUTTER_TIMELINE_FORWARD;

    printf("reverse_timeline %d\n", width);

    clutter_actor_save_easing_state(progress_rect);
    clutter_actor_set_width(progress_rect, width);
    clutter_actor_restore_easing_state(progress_rect);


    clutter_timeline_set_direction (timeline, dir);
}

int main(int argc , char * argv[])
{
    ClutterTimeline *timeline;
    ClutterActor *progress_rect = NULL;

    if (clutter_init (&argc, &argv) != CLUTTER_INIT_SUCCESS)
    {
        return EXIT_FAILURE;
    }

    ClutterActor *stage = clutter_stage_new();
    clutter_stage_set_title (CLUTTER_STAGE (stage), "ClutterSignal");
    clutter_stage_set_user_resizable (CLUTTER_STAGE (stage), TRUE);
    clutter_actor_set_size(stage, WINDOWS_WIDTH, WINDOWS_HEIGHT);
    clutter_actor_set_background_color (stage, CLUTTER_COLOR_Green);
    g_signal_connect (stage, "destroy", G_CALLBACK (clutter_main_quit), NULL);

    /* a progress bar */
    progress_rect = clutter_actor_new ();
    clutter_actor_set_background_color (progress_rect, CLUTTER_COLOR_DarkChameleon);
    clutter_actor_set_position (progress_rect, 50, 225);
    clutter_actor_set_size (progress_rect, 200, 50);
    clutter_actor_add_child (stage, progress_rect);

    timeline = clutter_timeline_new (100);
    clutter_timeline_set_repeat_count (timeline, -1);
    clutter_timeline_set_auto_reverse (timeline, TRUE);
    g_signal_connect (timeline, "completed", G_CALLBACK (reverse_timeline), progress_rect);
    clutter_timeline_start (timeline);

    clutter_actor_show (stage);
    clutter_main();
    g_object_unref(timeline);
    return EXIT_SUCCESS;
}